package ipc

import "encoding/json"
import "fmt"

type IpcClient struct {
	conn chan string
}	

func NewIpcClient(server *IpcServer) *IpcClient {
	c := server.Connect()
	return &IpcClient{
		c,
	}
}

func (client *IpcClient)Call(method, params string) (resp *Response, err error) {
	req := &Request{
		method, 
		params,
	}

	var b []byte
	b, err = json.Marshal(req)
	if err != nil {
		fmt.Println("Invalid request format: ", req)
		return
	}

	client.conn <- string(b)
	str := <- client.conn 	// 等待返回值

	var rawResp Response
	err = json.Unmarshal([]byte(str), &rawResp)
	resp = &rawResp

	return
}

func (client *IpcClient)Close() {
	client.conn <- "CLOSE"
}